from django.shortcuts import render, redirect
from app01 import models


def depart_list(request):
    """部门列表"""
    page_name = "部门列表"
    queryset = models.Department.objects.all()
    return render(request, 'depart_list.html', {'departments': queryset, 'page_name': page_name})


def depart_add(request):
    """新建部门"""
    page_name = "新建部门"
    if request.method == "GET":
        # GET方式访问，呈现新建页面
        return render(request, 'depart_add.html', {'page_name': page_name})
    # 填写信息以POST方式提交
    # 获取部门名称
    title = request.POST['title']
    # 数据库中创建部门
    models.Department.objects.create(title=title)
    # 重定向到部门列表记录
    return redirect('/depart/list/')


def depart_delete(request):
    """删除部门"""
    # 获得要删除的记录id
    nid = request.GET.get('nid')
    # 根据nid删除数据库记录
    models.Department.objects.filter(id=nid).delete()
    # 重定向到部门列表页面
    return redirect('/depart/list/')


def depart_edit(request, nid):
    """编辑部门"""
    page_name = "编辑部门"

    if request.method == "GET":
        # 根据nid筛选获得部门记录，并在返回页面时使用该值进行填充
        row_object = models.Department.objects.filter(id=nid).first()
        # 返回编辑部门页面
        return render(request, 'depart_edit.html', {'row_object': row_object, 'page_name': page_name})

    # 更新数据库记录
    title = request.POST['title']
    models.Department.objects.filter(id=nid).update(title=title)
    return redirect('/depart/list/')
